<?php
/**
 * RoomController
 *
 * PHP Version 5.4
 *
 * @author baohui <baohui@icesmart.cn>
 */

namespace Admin\Controller;

use Admin\Service\BaseService;
use Admin\Service\PermissionService;
use Admin\Service\UserService;
use Api\Controller\ServiceController;
use Model\AdModel;
use Model\LiveSettingModel;
use Model\LiveUrlModel;
use Model\PaperModel;
use Model\QuestionModel;
use Model\TeacherModel;
use Model\UserModel;
use Think\Controller;
use Model\RoomModel;
use Model\LiveCateogyModel;

class RoomController extends BaseController
{

    protected $userInfo;

    public function __construct()
    {
        parent::__construct();
        $userService = new UserService();
        $this->userInfo = $userService->validateLogin(); //验证是否登录

        $permissionService = new PermissionService();
        $permission = $permissionService->validate($this->userInfo['userId'], [
            'add' => '/' . CONTROLLER_NAME . '/addRoom',
            'del' => '/' . CONTROLLER_NAME . '/deleteRoom',
            'edit' => '/' . CONTROLLER_NAME . '/editRoom',
            'changeRoomStatus' => '/' . CONTROLLER_NAME . '/changeRoomStatus',
            'categoryStatus' => '/' . CONTROLLER_NAME . '/changeStatus',
            'editCategory' => '/' . CONTROLLER_NAME . '/editCategory',
            'addCategory' => '/' . CONTROLLER_NAME . '/addCategory',
            'delCategory' => '/' . CONTROLLER_NAME . '/delete',
            'addBind' => '/' . CONTROLLER_NAME . '/addBind',
            'editRoomBind' => '/' . CONTROLLER_NAME . '/editRoomBind',
            'deleteRoomBind' => '/' . CONTROLLER_NAME . '/deleteRoomBind',
            'changePaper' => '/' . CONTROLLER_NAME . "/changePaper"
        ]);


        $menu = $permissionService->menu($this->userInfo['userId']);

        $this->assign('menu', $menu);
        $this->assign('permission', $permission);
        $this->assign("userInfo", $this->userInfo);
    }

    /**
     * 直播间列表
     *
     */
    public function index()
    {
        $roomsModel = new RoomModel();
        $page = $this->page($roomsModel, null);
        $show = $page->show();
        $limit[] = $page->firstRow;
        $limit[] = $page->listRows;
        $roomList = $roomsModel->findByFilter(null, ['id' => 'DESC'], $limit);
        $userModel = new UserModel();
        foreach ($roomList as $k => $v) {
            $userInfo = $userModel->get($v['userId']);
            $roomList[$k]['username'] = $userInfo['nickname'];
        }
        $liveSettingModel = new LiveSettingModel();
        foreach ($roomList as $k => $v) {
            $liveSetting = $liveSettingModel->where("`roomId` = '{$v['id']}' AND `paperId` > 0")->find();
            $roomList[$k]['liveSetting'] = empty($liveSetting) ? false : true;
        }

        //获取流通道名称
        $liveUrlModel = new LiveUrlModel();
        foreach ($roomList as $k => $v) {
            $liveUrlInfo = $liveUrlModel->where('roomId = ' . $v['id'])->find();
            $roomList[$k]['channel'] = $liveUrlInfo['channel'];
        }

        $categoryModel = new LiveCateogyModel();
        foreach ($roomList as $k => $v) {
            $roomList[$k]['categoryInfo'] = $categoryModel->get($v['categoryId']);
            $roomList[$k]['parentCategory'] = $categoryModel->get($roomList[$k]['categoryInfo']['categoryId']);
        }
        $parentsCategoryList = $categoryModel->findByFilter(['categoryId' => 0, 'status' => 1]);
        $childCategoryList = $categoryModel->where("`categoryId` != 0 AND `status` = 1")->select();

        //获取未绑定主播
        $userModel = new UserModel();
        $userList = $userModel->findByFilter(['permission' => 1, 'status' => 1], ['createTime' => 'DESC']);
        $roomUserList = $roomsModel->queryUser();

        foreach ($userList as $k => $v) {
            foreach ($roomUserList as $roomUsers) {
                if ($v['id'] == $roomUsers['userId']) {
                    unset($userList[$k]);
                }
            }
        }

        $this->assign('url', '/Room/index');
        $this->assign('userList', $userList);
        $this->assign("parentsCategoryList", $parentsCategoryList);
        $this->assign("childCategoryList", json_encode($childCategoryList));
        $this->assign('roomList', $roomList);
        $this->assign("page", $show);
        $this->display();
    }

    /**
     * 变更直播间所绑定的试卷状态
     *
     *
     * @param int $roomId 直播间Id
     * @param int $status 状态
     *
     */
    public function changePaper()
    {
        $data['id'] =I("get.roomId");
        $data['isOpenPaper'] =I("get.status");
        $roomModel = new RoomModel();
        $updataRoom = $roomModel->save($data);
        if($updataRoom){
            $this->success("变更试卷状态成功");
        }else{
            $this->error("变更试卷状态失败！");
        }
    }

    /**
     * 添加直播间
     *
     * @param string $name 直播间名称
     * @param string $description 直播间介绍
     * @param int $categoryId 分类ID
     * @param int $userId 用户ID
     *
     *
     */
    public function addRoom()
    {
        $name = $this->request->post('name');
        $beginTime = $this->request->post('beginTime');
        $description = $this->request->post('description');
        $categoryId = intval($this->request->post('categoryId'));
        $userId = intval($this->request->post('userId'));
        $image = $_FILES['image'];

        if (empty($name)) {
            $this->error("房间名称不可为空！");
        }

        if (!empty($image['name'])) {
            $baseService = new BaseService();
            $image = $baseService->upload($image);
            $data['image'] = $image;
        }

        if (!empty($userId)) {
            $userModel = new UserModel();
            $userInfo = $userModel->get($userId);
            $data['username'] = $userInfo['nickname'];
        }

        $data['name'] = $name;
        $data['description'] = $description;
        $data['categoryId'] = $categoryId;
        $data['userId'] = $userId;
        $data['createTime'] = date('Y-m-d h:l:s');
        $data['beginTime'] = strtotime($beginTime);

        $roomModel = new RoomModel();
        $roomId = $roomModel->add($data);
        if ($roomId) {
            $roomNum = $roomModel->where(" id = {$roomId}")->setInc("roomNumber", $roomId + 1000);
            if ($roomNum) {
                $this->success("添加成功");
            } else {
                $this->error("变更房间号失败！");
            }
        } else {
            $this->error("添加失败");
        }

    }

    /*
    * 变更直播间状态
    *
    * @param int $status       分类状态
    * @param int $roomId   直播间ID
    *
    */
    public function changeRoomStatus()
    {
        $status = $this->request->get('status');
        $roomId = intval($this->request->get('roomId'));
        $roomModel = new RoomModel();
        $findRoom = $roomModel->get($roomId);
        if ($findRoom['userId'] == 0) {
            $this->error("当前直播间无主播，无法对外开放！");
        }

        //1.关闭直播间状态
        $updateRoom = $roomModel->update(['status' => $status], $roomId);

        //2.关闭流通道
        $LiveUrlModel = new LiveUrlModel();
        $LiveUrlInfo = $LiveUrlModel->buildQueryFilter(['roomId' => $roomId])->find();
        $channel = $LiveUrlInfo['channel'];

        $apiService = new ServiceController();
        $stream = $apiService->getStream($channel);
        $cid = $stream['publish']['cid'];
        if (!empty($cid)) {
            $apiService->offStream($cid);
        }

        if ($updateRoom) {
            $this->success("变更状态成功！");
        } else {
            $this->error("变更状态失败");
        }
    }

    /**
     * 删除直播间
     *
     * @param int $roomId 直播间ID
     */
    public function deleteRoom()
    {
        $roomId = intval($this->request->get('roomId'));
        $roomModel = new RoomModel();
        $deleteRoom = $roomModel->delete($roomId);

        //解绑流通道
        $LiveUrlModel = new LiveUrlModel();
        $LiveUrlInfo = $LiveUrlModel->buildQueryFilter(['roomId' => $roomId])->find();
        $LiveUrlResult = true;
        if ($LiveUrlInfo) {
            $LiveUrlResult = $LiveUrlModel->buildQueryFilter(['roomId' => $roomId])->setField('roomId', 0);
        }

        if ($deleteRoom && $LiveUrlResult) {
            $this->success("删除成功!");
        } else {
            $this->error("删除失败");
        }
    }

    /**
     * 修改分类模板
     *
     * @param int $roomId 直播间ID
     */
    public function editRoom()
    {
        $id = intval($this->request->get('roomId'));
        if (empty($id)) {
            $this->error("非法操作");
        }
        $roomModel = new RoomModel();
        $room = $roomModel->get($id);

        $categoryModel = new LiveCateogyModel();
        $parentsCategoryList = $categoryModel->findByFilter(['categoryId' => 0, 'status' => 1]);
        $childCategoryList = $categoryModel->where("`categoryId` != 0 AND `status` = 1")->select();
        $findCategory = $categoryModel->get($room['categoryId']);

        //获取未绑定主播
        $userModel = new UserModel();
        $userList = $userModel->findByFilter(['permission' => 1, 'status' => 1], ['createTime' => 'DESC']);
        $roomUserList = $roomModel->queryUser();

        foreach ($userList as $k => $v) {
            foreach ($roomUserList as $roomUsers) {
                if ($v['id'] == $roomUsers['userId']) {
                    if ($roomUsers['userId'] != $room['userId']) {
                        unset($userList[$k]);
                    }
                }
            }
        }

        $this->assign('url', '/Room/index');
        $this->assign('userList', $userList);
        $this->assign("findCategory", $findCategory);
        $this->assign("parentsCategoryList", $parentsCategoryList);
        $this->assign("childCategoryList", json_encode($childCategoryList));
        $this->assign("room", $room);
        $this->display();
    }

    /**
     * 修改直播间
     *
     * @param string $name 直播间名称
     * @param string $description 直播间介绍
     * @param int $categoryId 分类ID
     * @param int $userId 用户ID
     * @param int $roomId 用户ID
     *
     *
     */
    public function modifyRoom()
    {
        $id = intval($this->request->post('id'));
        $beginTime = $this->request->post('beginTime');
        $name = $this->request->post('name');
        $description = $this->request->post('description');
        $categoryId = intval($this->request->post('categoryId'));
        $userId = intval($this->request->post('userId'));
        $status = $this->request->post('status');
        $image = $_FILES['image'];

        if (!empty($image['name'])) {
            $baseService = new BaseService();
            $image = $baseService->upload($image);
            $data['image'] = $image;
        }

        if (!empty($userId)) {
            $userModel = new UserModel();
            $userInfo = $userModel->get($userId);
            $data['username'] = $userInfo['nickname'];
        }

        $data['name'] = $name;
        $data['beginTime'] = strtotime($beginTime);
        $data['description'] = $description;
        $data['categoryId'] = $categoryId;
        $data['userId'] = $userId;
        $data['status'] = $status;

        if ($userId == 0 && $status == 1) {
            $this->error("当前直播间暂无主播，无法开启");
        }
        if (empty($data['name'])) {
            $this->error("分类名称不可为空");
        }
        $roomModel = new RoomModel();
        $room = $roomModel->update($data, $id);

        /**/
        $bannerModel = new AdModel();
        if ($status == 0) {
            $bannerModel->where('roomId = ' . $id)->setField('status', 0);
        }

        if ($room) {
            $this->success("修改成功");
        } else {
            $this->error("修改失败");
        }
    }

    /**
     * 直播分类列表
     *
     */
    public function category()
    {
        $categoryModel = new LiveCateogyModel();
        $parentsCategoryList = $categoryModel->findByFilter(['categoryId' => 0, 'status' => 1]);
        $categoryList = $categoryModel->select();
        $categoryList = $categoryModel->structure($categoryList);


        $this->assign('url', '/Room/category');
        $this->assign("categoryList", $categoryList);
        $this->assign("parentsCategoryList", $parentsCategoryList);
        $this->display();
    }

    /**
     * 添加分类
     *
     * @param string CategoryName       分类名称
     * @param int    CategoryParentsId  分类父类ID
     *
     */
    public function addCategory()
    {
        $parentsId = intval($this->request->post('parentsId'));
        $cateogryName = $this->request->post('name');
        $image = $_FILES['image'];

        if (empty($cateogryName) || empty($image['name'])) {
            $this->error("带*处为必填项");
        }

        $baseService = new BaseService();
        $image = $baseService->upload($image);

        $data = [
            'name' => $cateogryName,
            'image' => $image,
            'categoryId' => $parentsId,
            'createTime' => date('Y-m-d h:l:s')
        ];
        $cateogyModel = new LiveCateogyModel();
        $unique = $cateogyModel->validateField("name", $cateogryName, "unique");
        if ($unique) {
            $addCategory = $cateogyModel->add($data);
            if ($addCategory) {
                $this->success("添加成功！");
            } else {
                $this->error("添加失败");
            }
        } else {
            $this->error("分类已经存在");
        }
    }

    /*
     * 变更分类状态
     *
     * @param int $status       分类状态
     * @param int $cateogryId   分类ID
     *
     */
    public function changeStatus()
    {
        $status = intval($this->request->get('status'));
        $categoryId = intval($this->request->get('categoryId'));
        $categoryModel = new LiveCateogyModel();
        $updateCateogy = $categoryModel->update(['status' => $status], $categoryId);
        if ($updateCateogy) {
            $this->success("变更状态成功！");
        } else {
            $this->error("变更状态失败");
        }
    }

    /**
     * 删除分类
     *
     * @param int $categoryId 分类ID
     */
    public function delete()
    {
        $categoryId = intval($this->request->get('categoryId'));
        $categoryModel = new LiveCateogyModel();
        //当前分类下是否有房间,存在房间不可删除
        $roomModel = new RoomModel();
        $isRoomhas = $roomModel->findByFilter(['categoryId' => $categoryId]);
        if (!empty($isRoomhas)) {
            $this->error("房间ID为:" . $isRoomhas[0]['id'] . "已绑定此分类，不可删除！");
        }
        $deleteCategory = $categoryModel->delete($categoryId);
        if ($deleteCategory) {
            $this->success("删除成功!");
        } else {
            $this->error("删除失败");
        }

    }

    /**
     * 修改分类模板
     *
     * @param int $categoryId 分类ID
     */
    public function editCategory()
    {
        $id = intval($this->request->get('categoryId'));
        if (empty($id)) {
            $this->error("非法操作");
        }
        $categoryModel = new LiveCateogyModel();
        $parentsCategoryList = $categoryModel->findByFilter(['categoryId' => 0, 'status' => 1]);
        $category = $categoryModel->get($id);

        $this->assign('url', '/Room/category');
        $this->assign("parentsCategoryList", $parentsCategoryList);
        $this->assign("category", $category);
        $this->display();
    }

    /**
     * 修改分类
     *
     * @param string $name 分类名称
     * @param int $categoryId 分类所属上级ID
     * @param int $status 分类状态
     */
    public function modifyCategory()
    {
        $data = [
            'name' => $this->request->post('name'),
            'categoryId' => $this->request->post('categoryId'),
            'status' => $this->request->post('status')
        ];

        $image = $_FILES['image'];
        $id = intval($this->request->post('id'));
        if (empty($data['name'])) {
            $this->error("分类名称不可为空");
        }
        if (!empty($image['name'])) {
            $baseService = new BaseService();
            $image = $baseService->upload($image);
            $data['image'] = $image;
        }

        $categoryModel = new LiveCateogyModel();
        $category = $categoryModel->update($data, $id);
        if ($category) {
            $this->success("修改成功");
        } else {
            $this->error("修改失败");
        }
    }


    /**
     * 直播间绑定列表
     *
     */
    public function roomBind()
    {

        $teacherModel = new TeacherModel();
        $teacherList = $teacherModel->select();
        $roomModel = new RoomModel();
        $liveUrlModel = new LiveUrlModel();
        $liveSettingModel = new LiveSettingModel();
        $page = $this->page($liveSettingModel, null);
        $show = $page->show();
        $liveSettingList = $liveSettingModel->table('live_rooms rooms,live_setting setting,live_urls urls')->where('setting.roomId = rooms.id and setting.liveUrlId = urls.id')->field('rooms.name, rooms.roomNumber,urls.address,urls.channel,setting.id,setting.liveUrlId,setting.roomId,setting.remark')->limit($page->firstRow . ',' . $page->listRows)->select();
        $roomList = $roomModel->findByFilter(['liveUrlId' => 0]);
        $liveUrlList = $liveUrlModel->findByFilter(['roomId' => 0]);

        $paperModel = new PaperModel();
        $paper = $paperModel->select();

        $this->assign("paper", $paper);
        $this->assign('url', '/Room/roomBind');
        $this->assign("teacherList", $teacherList);
        $this->assign('roomList', $roomList);
        $this->assign('liveUrlList', $liveUrlList);
        $this->assign('liveSettingList', $liveSettingList);
        $this->assign("page", $show);
        $this->display();
    }

    /**
     * 绑定直播间与直播地址
     *
     * @param int $roomId 房间ID
     * @param int $liveUrlId 直播地址ID
     * @param string $remark 绑定信息
     */
    public function addBind()
    {
        $paperId = intval($this->request->post('paperId'));
        $roomId = intval($this->request->post('roomId'));
        $liveUrlId = intval($this->request->post('liveUrlId'));
        $teacherId = intval($this->request->post('teacherId'));
        $remark = $this->request->post('remark');
        $data = [
            'paperId' => $paperId,
            'teacherId' => $teacherId,
            'roomId' => $roomId,
            'liveUrlId' => $liveUrlId,
            'remark' => $remark,
            'createTime' => date('Y-m-d H:i:s')
        ];
        if (empty($roomId) || empty($liveUrlId)) {
            $this->error("非法参数请求");
        }
        $liveSettingModel = new LiveSettingModel();
        $roomModel = new RoomModel();
        $liveUrlModel = new LiveUrlModel();

        $liveSettingModel->startTrans();
        $insertLiveSetting = $liveSettingModel->add($data);
        $changeRoom = $roomModel->update(['liveUrlId' => $liveUrlId], $roomId);
        $changeLiveUrl = $liveUrlModel->update(['roomId' => $roomId], $liveUrlId);
        if ($insertLiveSetting && $changeLiveUrl && $changeRoom) {
            $liveSettingModel->commit();
            $this->success("绑定成功");
        } else {
            $liveSettingModel->rollback();
            $this->error("绑定失败");
        }
    }

    /**
     * 修改绑定信息
     *
     * @param int $settingId 绑定直播地址ID
     */
    public function editRoomBind()
    {
        $teacherModel = new TeacherModel();
        $teacherList = $teacherModel->select();

        $settingId = intval($this->request->get('id'));
        $liveSettingModel = new LiveSettingModel();
        $roomModel = new RoomModel();
        $liveUrlModel = new LiveUrlModel();
        $liveSetting = $liveSettingModel->get($settingId);
        $room = $roomModel->get($liveSetting['roomId']);
        //当前空闲的直播地址
        $liveUrlList = $liveUrlModel->findByFilter(['roomId' => 0]);
        //当前选中的直播地址
        $liveUrl = $liveUrlModel->get($liveSetting['liveUrlId']);

        $liveUrlCount = count($liveUrlList);
        $liveUrlList[$liveUrlCount] = $liveUrl;
        $paperModel = new PaperModel();
        $paper = $paperModel->select();

        $this->assign("paper", $paper);
        $this->assign("teacherList", $teacherList);
        $this->assign('url', '/Room/roomBind');
        $this->assign("liveSetting", $liveSetting);
        $this->assign('liveUrlList', $liveUrlList);
        $this->assign("room", $room);
        $this->display();
    }

    /**
     * 修改直播间与直播地址绑定
     *
     * @param  int $liveUrlId 绑定的直播地址ID
     * @param  int $id 绑定表ID
     * @param  string $remark 备注信息
     *
     */
    public function modifyLiveSetting()
    {
        $paperId = intval($this->request->post('paperId'));
        $teacherId = intval($this->request->post('teacherId'));
        $liveUrlId = intval($this->request->post('liveUrlId'));
        $remark = $this->request->post('remark');
        $id = intval($this->request->post('id'));
        $liveSettingModel = new LiveSettingModel();
        $liveUrlModel = new LiveUrlModel();
        $liveSetting = $liveSettingModel->get($id);
        $liveSettingModel->startTrans();
        //是否修改了直播地址
        $isEditUrls = false;
        //更新是否成功
        $isSuccess = true;
        //如果更改了直播地址，需要联表变更状态
        if ($liveUrlId != $liveSetting['liveUrlId']) {
            $isEditUrls = true;
            $settingData['liveUrlId'] = $liveUrlId;
            $freeLiveUrl = $liveUrlModel->update(['roomId' => 0], $liveSetting['liveUrlId']);
            $bindLiveUrl = $liveUrlModel->update(['roomId' => $liveSetting['roomId']], $liveUrlId);
        }
        $settingData['teacherId'] = $teacherId;
        $settingData['paperId'] = $paperId;
        $settingData['remark'] = $remark;
        $settingData['updateTime'] = date('Y-m-d H:i:s');
        $updateLiveSetting = $liveSettingModel->update($settingData, $id);

        if ($isEditUrls) {
            if ($updateLiveSetting && $freeLiveUrl && $bindLiveUrl) {
                $liveSettingModel->commit();
            } else {
                $liveSettingModel->rollback();
                $isSuccess = false;
            }
        } else {
            if ($updateLiveSetting) {
                $liveSettingModel->commit();
            } else {
                $liveSettingModel->rollback();
                $isSuccess = false;
            }
        }
        if ($isSuccess) {
            $this->success("修改成功");
        } else {
            $this->error("修改失败");
        }

    }


    /**
     * 删除绑定信息
     *
     * @param int $id 绑定直播地址ID
     */
    public function deleteRoomBind()
    {

        $id = intval($this->request->get('id'));
        $liveSettingModel = new LiveSettingModel();
        $roomModel = new RoomModel();
        $liveUrlModel = new LiveUrlModel();
        $liveSetting = $liveSettingModel->get($id);
        $liveSettingModel->startTrans();

        $deleteLiveSetting = $liveSettingModel->delete($id);
        $freeLiveUrl = $liveUrlModel->update(['roomId' => 0], $liveSetting['liveUrlId']);
        $room = $roomModel->update(['liveUrlId' => 0], $liveSetting['roomId']);
        if ($deleteLiveSetting && $freeLiveUrl && $room) {
            $liveSettingModel->commit();
            $this->success("解绑成功");
        } else {
            $liveSettingModel->rollback();
            $this->error("解绑失败");
        }
    }
} 